// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package trace_dao

import (
	"strings"
	"time"

	"gitcode.com/opendragonfly/df_proto_gen_go.git/trace_api"
	"github.com/dgraph-io/badger/v4"
	"google.golang.org/protobuf/proto"
)

const (
	_FULL_TRACE_NAME_SPACE = "fullTrace"
)

type _FullTraceTable struct{}

func (table *_FullTraceTable) genKey(serviceInfo *trace_api.ServiceInfo, traceId string) []byte {
	name := strings.Join([]string{_FULL_TRACE_NAME_SPACE, serviceInfo.ServiceName, serviceInfo.ServiceVersion, traceId}, "\t")
	return []byte(name)
}

func (table *_FullTraceTable) Insert(txn *badger.Txn, traceInfo *trace_api.TraceFullInfo, keepTraceDay uint) error {
	key := table.genKey(traceInfo.Service, traceInfo.TraceId)
	value, err := proto.Marshal(traceInfo)
	if err != nil {
		return err
	}
	entry := badger.NewEntry(key, value).WithTTL(time.Duration(keepTraceDay) * time.Hour * 24)
	return txn.SetEntry(entry)
}

func (table *_FullTraceTable) Get(txn *badger.Txn, serviceInfo *trace_api.ServiceInfo, traceId string) (*trace_api.TraceFullInfo, error) {
	key := table.genKey(serviceInfo, traceId)
	item, err := txn.Get(key)
	if err != nil {
		return nil, err
	}
	value, err := item.ValueCopy(nil)
	if err != nil {
		return nil, err
	}
	traceInfo := &trace_api.TraceFullInfo{}
	err = proto.Unmarshal(value, traceInfo)
	return traceInfo, err
}
